package demo1;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 翻译软件
 */
public class UDPDictServe {
    private DatagramSocket serve;
    private Map<String,String> dictionary=new HashMap<>();

    public UDPDictServe(int port) throws SocketException {
        if(port<1024||port>65535) throw new BindException("端口不合法");
        serve=new DatagramSocket(port);
        dictionary.put("猪","pig");
        dictionary.put("狗","dog");
        dictionary.put("猫","cat");
        dictionary.put("猴","monkey");
        dictionary.put("老虎","tiger");
        dictionary.put("龙","dragon");

    }

    public void start() throws IOException {
        System.out.println("服务器已经启动");
        while (true){
            //接受用户的请求
            DatagramPacket request=new DatagramPacket(new byte[1024],1024);
            serve.receive(request);
            //解析用户发来的请求
            String requestString=new String(request.getData(),0,request.getLength(),"UTF-8");
            String responseString = process(requestString);
            //回应用户
            DatagramPacket response=new DatagramPacket(
                    responseString.getBytes(StandardCharsets.UTF_8),
                    0,
                    responseString.getBytes().length,
                    request.getSocketAddress()
            );
            serve.send(response);
            //打印日志
            System.out.println("request: "+requestString+" response: "+responseString+" "+request.getAddress()+" "+request.getPort());


        }
    }

    private String process(String requestString) {
        String string=dictionary.getOrDefault(requestString,"查无此词语");

        return  string;
    }

    public static void main(String[] args) throws IOException {
        UDPDictServe udpDictServe=new UDPDictServe(9999);
        udpDictServe.start();
    }
}
